package com.echat.serviceapigateway.security.config;

import com.echat.serviceapigateway.security.interceptor.AdminUserInterceptor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Created by chenmohan on 2018/08/28
 *
 * @description SpringWebMvc相关配置类
 */
@Configuration
@Log4j2
public class WebSecurityConfig implements WebMvcConfigurer {

    @Autowired
    AdminUserInterceptor adminUserInterceptor;

    /**
     * 配置admin页面资源的拦截路径和放行路径
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(adminUserInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/admin/login.html", "/admin/login/**", "/admin/hack");
    }

    /**
     * 配置静态资源
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
    }

    /**
     * 是否采用扩展名来确定responseBody的格式,比如 /foo.xml --> 返回Xml格式数据 , /foo.json --> 返回json格式数据
     * @param configurer
     */
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }

    /**
     * 基于BCrpt的加解密工具,来自于Spring-Security,adminUser的登录功能会使用到它
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
